package de.schnocklake.android.sap.crm;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import de.schnocklake.android.sap.crm.datamodel.Item;
import de.schnocklake.android.sap.crm.datamodel.Product;
import de.schnocklake.android.sap.crm.searchhelp.CRMProductValueHelpAdapter;
import de.schnocklake.android.sap.searchhelp.SAPValueHelpSoapAdapter;

public class ItemLine {
	private Activity activity; // calling activity
	private LayoutInflater mInflater;
	private AutoCompleteTextView productAutoCompleteTextView;
	// reference to table layout where the rows have to be added
	private TableLayout tableLayout;

	// the rows that are added to table
	private TableRow line1Edit;
	private TableRow line1Display;
	private TableRow line2Edit;
	private TableRow line2Display;

	private Handler longClickHandler;

	// datamodel "item"
	Item item;

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public ItemLine(Item mItem, Activity mActivity, TableLayout mTableLayout,
			Handler mLongClickHandler) {
		this.activity = mActivity;
		this.tableLayout = mTableLayout;
		this.longClickHandler = mLongClickHandler;
		this.item = mItem;

		// initiate layout - create the table rows and add them to table
		mInflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		line1Edit = (TableRow) mInflater.inflate(R.layout.itemeditrow1,
				tableLayout, false);
		line1Display = (TableRow) mInflater.inflate(R.layout.itemdisplayrow1,
				tableLayout, false);
		line2Edit = (TableRow) mInflater.inflate(R.layout.itemeditrow2,
				tableLayout, false);
		line2Display = (TableRow) mInflater.inflate(R.layout.itemdisplayrow2,
				tableLayout, false);
		tableLayout.addView(line1Edit);
		tableLayout.addView(line1Display);
		tableLayout.addView(line2Edit);
		tableLayout.addView(line2Display);

		// init widgets - values and value change listeners

		// unit picker - no selections possible, because no product - units
		// relate to the product - is selected right now
		setUnitValues(new String[] {});
		((Spinner) line2Edit.findViewById(R.id.UnitSpinner))
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						// update datamodel with selected unit
						String unit = parent.getAdapter().getItem(position)
								.toString();
						item.setUnit(unit);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
					}

				});

		// product selection field
		SAPValueHelpSoapAdapter autocomplete_adapter = new CRMProductValueHelpAdapter(
				activity);

		productAutoCompleteTextView = (AutoCompleteTextView) line1Edit
				.findViewById(R.id.ProductAutoCompleteTextView);
		productAutoCompleteTextView.setAdapter(autocomplete_adapter);
		productAutoCompleteTextView
				.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// product selected, update product in datemodel
						Product product = (Product) parent.getAdapter()
								.getItem(position);
						item.setProduct(product);

						InputMethodManager imm = (InputMethodManager) ItemLine.this.activity
								.getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(
								((EditText) productAutoCompleteTextView)
										.getWindowToken(), 0);

					}
				});

		// implement value change listeners
		OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				Log.i("CRMDroid", "View = + " + v.toString() + " hasFocus = "
						+ hasFocus);
				if (!hasFocus) {
					// when a widget lost focus, evaluate the value and update
					// the datamodel

					switch (v.getId()) {
					case R.id.QuantityEditText:
						item.setQuantity(Double.parseDouble(((EditText) v)
								.getText().toString()));
						InputMethodManager imm = (InputMethodManager) ItemLine.this.activity
								.getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(((EditText) v)
								.getWindowToken(), 0);

					}
				}
			}
		};
		line2Edit.findViewById(R.id.QuantityEditText).setOnFocusChangeListener(
				onFocusChangeListener);

		// implement reaction to changes values --- update displayfields

		PropertyChangeListener itemAndProductPropertyChangeListener = new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getPropertyName().equalsIgnoreCase("product")) {
					Product product = (Product) event.getNewValue();
					setUnitValues(new String[] {});
					product.addPropertyChangeListener(this);
					((TextView) line1Display
							.findViewById(R.id.ItemProductTextView))
							.setText(product.getPRODUCT_ID() + ", "
									+ product.getSHTEXT_LARGE());
					new ReadProductDetailTask().execute(new String[] {});
				} else if (event.getPropertyName().equalsIgnoreCase("quantity")) {
					Double quantity = (Double) event.getNewValue();
					((TextView) line2Display
							.findViewById(R.id.ItemQuantityDisplayTextView))
							.setText(Double.toString(quantity));
				} else if (event.getPropertyName().equalsIgnoreCase("unit")) {
					String unit = (String) event.getNewValue();
					((TextView) line2Display
							.findViewById(R.id.ItemUnitDisplayTextView))
							.setText(unit);
				} else if (event.getPropertyName().equalsIgnoreCase("units")) {
					String unitValues[] = (String[]) event.getNewValue();
					setUnitValues(unitValues);
				}
			}
		};
		item.addPropertyChangeListener(itemAndProductPropertyChangeListener);

		// notify the handler in createquotation class, that this item was
		// longclicked.
		// the user than can select to edit or delete this line
		OnLongClickListener onLongClickListener = new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				longClickHandler.dispatchMessage(longClickHandler
						.obtainMessage(1, ItemLine.this));
				return false;
			}
		};
		line1Display.setOnLongClickListener(onLongClickListener);
		line2Display.setOnLongClickListener(onLongClickListener);
	}

	/**
	 * Sets selectable units.
	 * 
	 * @param units
	 */
	public void setUnitValues(String units[]) {
		Spinner unitSpinner = (Spinner) line2Edit
				.findViewById(R.id.UnitSpinner);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
				android.R.layout.simple_spinner_item, units);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		unitSpinner.setAdapter(adapter);
	}

	public void setEditStatus(boolean editStatus) {
		if (editStatus) {
			line1Display.setVisibility(View.GONE);
			line2Display.setVisibility(View.GONE);
			line1Edit.setVisibility(View.VISIBLE);
			line2Edit.setVisibility(View.VISIBLE);
		} else {
			line1Display.setVisibility(View.VISIBLE);
			line2Display.setVisibility(View.VISIBLE);
			line1Edit.setVisibility(View.GONE);
			line2Edit.setVisibility(View.GONE);
		}
	}

	public void updateValues() {
		// it is possible, that the vale of the item quantity is not
		// automatically updated, because the item-object will be
		// notified when the field lost focus, not when the value changes
		item.setQuantity(Double.parseDouble(((EditText) line2Edit
				.findViewById(R.id.QuantityEditText)).getText().toString()));
	}

	public void removeTableRows() {
		tableLayout.removeView(line1Edit);
		tableLayout.removeView(line1Display);
		tableLayout.removeView(line2Edit);
		tableLayout.removeView(line2Display);
	}

	private class ReadProductDetailTask extends
			AsyncTask<String, Integer, String[]> {
		protected String[] doInBackground(String... dummy) {
			return item.getProduct().readProductDetail();
		}

		protected void onProgressUpdate(Integer... progress) {
		}

		protected void onPostExecute(String[] units) {
			item.getProduct().setUnits(units);
			item.setUnit(units[0]);
		}

	}

}
